package com.zhongjian.technologycal.mall.activity.personal.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongjian.technologycal.mall.R;
import com.zhongjian.technologycal.mall.adapter.AllOrderAdapter;
import com.zhongjian.technologycal.mall.base.BaseFragment;
import com.zhongjian.technologycal.mall.bean.CartBean;
import com.zhongjian.technologycal.mall.bean.OrderBean;
import com.zhongjian.technologycal.mall.bean.OrdersModelBean;
import com.zhongjian.technologycal.mall.bean.UserInfoBean;
import com.zhongjian.technologycal.mall.interfacemall.OrderInterface;
import com.zhongjian.technologycal.mall.net.HttpRetrofitClient;
import com.zhongjian.technologycal.mall.utils.LoadingTip;
import com.zhongjian.technologycal.mall.utils.NetWorkUtils;
import com.zhongjian.technologycal.mall.utils.ToastUitl;
import com.zhongjian.technologycal.mall.utils.UserUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.ResponseBody;
import rx.Subscriber;

/**
 * Created by wei on 2017/12/15.
 * 全部的订单列表
 */

public class AllOrderListFragment extends BaseFragment {
    public static final String CATEGORY_NAME = "com.nanchen.aiyagirl.module.category.CategoryFragment.CATEGORY_NAME";
    @BindView(R.id.lv_order_listView)
    ListView lv_order_listView;
    @BindView(R.id.loadedTip)
    LoadingTip loadingTip;
    @BindView(R.id.all_order_RefreshLayout)
    RefreshLayout refreshLayout;
    private AllOrderAdapter allOrderAdapter;
    private List<OrdersModelBean> listItems = new ArrayList<>();
    private int page = 0;
    private int pageNum = 10;
    public static String userName;

    @Override
    protected void initView() {
        allOrderAdapter = new AllOrderAdapter(getActivity(), listItems, new OrderInterface() {
            @Override
            public void isRefreshAll(boolean isSuccess) {
                if(isSuccess){
                    initRequest();
                }
            }
        });
        lv_order_listView.setAdapter(allOrderAdapter);
        initRequest();
        initViewPersonInfo();
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshlayout) {
                page = 0;
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initRequest();
                        refreshlayout.finishRefresh();
                        refreshlayout.setLoadmoreFinished(false);
                    }
                }, 1000);
            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(final RefreshLayout refreshlayout) {
                page++;
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initRequest();
                        refreshlayout.finishLoadmore();
                    }
                }, 1000);
            }
        });

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_all_orderlist;
    }


    public static AllOrderListFragment newInstance(String mCategoryName) {
        AllOrderListFragment categoryFragment = new AllOrderListFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CATEGORY_NAME, mCategoryName);
        categoryFragment.setArguments(bundle);
        return categoryFragment;
    }

    @Override
    public void initPresenter() {
//        initRequest();
    }

    /**
     * 订单列表请求
     */
    private void initRequest() {
        if (!NetWorkUtils.isNetConnected(getActivity())) {
            loadingTip.setLoadingTip(LoadingTip.LoadStatus.error);
            return;
        }
        HttpRetrofitClient.getInstance(getActivity())
                .getUrlRequestOrderList(UserUtils.getUserToken(),
                        "all", page, pageNum, new Subscriber<ResponseBody>() {
                            @Override
                            public void onStart() {
                                super.onStart();
                                loadingTip.setLoadingTip(LoadingTip.LoadStatus.loading);

                            }

                            @Override
                            public void onCompleted() {
                                if (listItems.size() <= 0) {
                                    loadingTip.setLoadingTip(LoadingTip.LoadStatus.empty);
                                }


                            }

                            @Override
                            public void onError(Throwable e) {
                                loadingTip.setLoadingTip(LoadingTip.LoadStatus.sereverError);
                            }

                            @Override
                            public void onNext(ResponseBody responseBody) {
                                loadingTip.setLoadingTip(LoadingTip.LoadStatus.finish);
                                try {
                                    Gson gson = new Gson();
                                    JSONObject jsonObject = new JSONObject(responseBody.string());
                                    if (jsonObject.optInt("error_code") == 0) {
                                        JSONArray jsonArray = jsonObject.optJSONArray("data");
                                        List<OrdersModelBean> forlist = gson.fromJson(jsonArray.toString(), new TypeToken<List<OrdersModelBean>>() {
                                        }.getType());
                                        setData(forlist);
                                    } else if (jsonObject.optInt("error_code") == 3) {
                                        Intent intent = new Intent();
                                        intent.setAction("com.broadcast.info_out_line");
                                        getActivity().sendBroadcast(intent);
                                    } else {
                                        ToastUitl.showShort("" + jsonObject.optString("error_message"));
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                        });
    }

    private void setData(List<OrdersModelBean> foreshowList) {
        if (page == 0) {
            listItems.clear();
        }
        for (OrdersModelBean vo : foreshowList) {
            listItems.add(vo);
        }
        allOrderAdapter.notifyDataSetChanged();
    }

    /**
     * 获取钱包数据
     */
    private void initViewPersonInfo() {
        if (!NetWorkUtils.isNetConnected(getActivity())) {
            ToastUitl.showShort(R.string.no_net);
            return;
        }
        HttpRetrofitClient.getInstance(getActivity()).getUrlRequestAccountBalance(UserUtils.getUserToken(),
                new Subscriber<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            Gson gson = new Gson();
                            UserInfoBean userInfoBean = gson.fromJson(responseBody.string(), UserInfoBean.class);
                            if (userInfoBean.getError_code() == 0) {
                                userName = userInfoBean.getData().getPersonDataMap().getUserName();
                            } else {
                                ToastUitl.showShort(userInfoBean.getError_message());
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });


    }
}
